<?php
namespace app\modules\content\controllers;

use app\libs\Pager;
use app\modules\content\models\Popup;
use yii;
use app\libs\ApiControl;
use app\libs\GetData;

class PopupController extends ApiControl
{
    public $enableCsrfValidation = false;
    public $port = [1=>'APP'];
    public $belong = [1=>'首页'];
    public $type = [1=>'活动',2=>'资讯',3=>'外链'];

    public function actionIndex()
    {
        $page = Yii::$app->request->get('page',1);
        $where = ' where 1=1';
        $offset = 15 * ($page - 1);
        $count = Yii::$app->db->createCommand("select count(id) as count from {{%popup}} $where")->queryOne();
        $url = '/content/popup/index?page';
        $count = $count['count'];
        $page = new Pager("$url", $count, $page, 15);
        $str = $page->GetPager();
        $data = Yii::$app->db->createCommand("select * from {{%popup}} $where order by id desc limit $offset,15")->queryAll();
        return $this->render('index', ['data' => $data,'str'=>$str,'port'=>$this->port,'belong'=>$this->belong,'type'=>$this->type]);
    }

    public function actionAdd()
    {
        if (!$_POST) {
            $id = Yii::$app->request->get('id', '');
            if (empty($id)) {
                $data = null;
            } else {
                $data = Yii::$app->db->createCommand("select * from {{%popup}} where id=" . $id)->queryOne();
            }
            return $this->render('add', ['data' => $data,'port'=>$this->port,'belong'=>$this->belong,'type'=>$this->type]);
        } else {
            $banner = new Popup();
            $getdata = new GetData();
            $must = array('port' => '所属端','belong'=>'位置' ,'pic' => '图片','type'=>'跳转类型','startTime'=>'有效期','endTime'=>'有效期');
            $data = $getdata->PostData($must, 'banner');
            $data['startTime'] = !empty($data['startTime']) ? strtotime($data['startTime']) : '';
            $data['endTime'] = !empty($data['endTime']) ? strtotime($data['endTime']) : '';
            if (empty($data['id'])) {
                $re = Yii::$app->db->createCommand()->insert("{{%popup}}", $data)->execute();
            } else {
                $re = $banner->updateAll($data, 'id=:id', array(':id' => $data['id']));
            }
            if ($re) {
                $this->redirect('index');
            } else {
                echo '<script>alert("数据修改/添加失败，请重试");history.go(-1);</script>';
                die;
            }
        }

    }

    public function actionDel()
    {
        $id = Yii::$app->request->get('id', '');
        $re = Popup::deleteAll("id=:id", array(':id' => $id));
        if ($re) {
            echo true;
        }

    }
}